package com.xiaogao.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.xiaogao.common.entity.TokenEntity;
import com.xiaogao.common.exception.BusinessException;
import com.xiaogao.common.utils.PasswordUtils;
import com.xiaogao.common.utils.RedisUtils;
import com.xiaogao.common.utils.token.JwtUtils;
import com.xiaogao.sys.model.SysRole;
import com.xiaogao.sys.model.SysUser;
import com.xiaogao.sys.request.LoginRequest;
import com.xiaogao.sys.service.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class LoginServiceImpl implements LoginService {
    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private SysLogLoginService sysLogLoginService;

    @Autowired
    private RedisUtils redisUtils;

    @Override
    public String login(LoginRequest loginRequest) {
        // 1、查询数据库用户名
        LambdaQueryWrapper<SysUser> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(SysUser::getUsername,loginRequest.getUsername());
        SysUser sysUser = sysUserService.getOne(wrapper);
        // 2、如果用户名不存在，返回用户名不存在！
        if (sysUser == null) {
            throw new BusinessException(500, "用户不存在！");
        }
        // 3、如果用户存在，比对密码,如果密码不对，返回密码错误！
        if (!PasswordUtils.matches(loginRequest.getPassword(), sysUser.getPassword())) {
            throw new BusinessException(500, "密码错误！");
        }
        // 4、如果密码正确，返回token

        // 查询dataScope
        String dataScope = "";
        if(JwtUtils.isAdmin(sysUser.getUsername())){
            dataScope = "3";
        }else{
            List<SysRole> sysRoles = sysRoleService.queryByUserId(sysUser.getId());
            List<String> dataScopeList = new ArrayList<>();
            if(sysRoles != null && !sysRoles.isEmpty()){
                dataScopeList = sysRoles.stream().map(SysRole::getDataScope).toList();
                dataScope = String.join(",",dataScopeList);
            }
        }
        TokenEntity tokenEntity = TokenEntity.builder()
                .userId(sysUser.getId())
                .realName(sysUser.getRealName())
                .username(sysUser.getUsername())
                .deptId(sysUser.getDeptId())
                .dataScopes(dataScope)
                .build();
        String token = JwtUtils.create(tokenEntity);

        // 5、把token保存在redis并设置有效期,2小时
        // username:token
        String key = loginRequest.getUsername().concat(":token");
        redisUtils.set(key, token, 60 * 60 * 2);

        // 6、添加登录日志-->异步操作
        sysLogLoginService.insert(sysUser.getId());
        return token;
    }
}
